/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.common.util.thread;

import com.enfry.common.util.String.Strings;


/**
 * 
 * 线程相关工具类
 * @Title com.enfry.util.Threads
 * @author Penghu
 * @date 2016年11月10日
 */
public class Threads
{
    /**
     * 获取调用者堆栈对象
     * 
     * @return  调用者堆栈
     */
    public static StackTraceElement getInvoker()
    {
        StackTraceElement[] elems = Thread.currentThread().getStackTrace();
        return elems[3];//0是Thread本身，1是Threads，2是getInvoker方法的使用者，3才是正主，引入getInvoker使用的调用者
    }
    
    /**
     * 获取调用者类名、方法名和行数
     * 
     * @return  调用者堆栈字符串
     */
    public static String getInvokerString()
    {
        StackTraceElement[] elems = Thread.currentThread().getStackTrace();
        StackTraceElement elem = elems[3];
        return new StringBuilder()
            .append("[").append(elem.getClassName()).append("]")
            .append("[").append(elem.getMethodName()).append("]")
            .append("[第").append(elem.getLineNumber()).append("行]")
            .toString();
    }
    
    /**
     * 获取调用者类名、方法名和行数简写
     * 
     * @return  调用者堆栈字符串
     */
    public static String getInvokerAbbr()
    {
        StackTraceElement[] elems = Thread.currentThread().getStackTrace();
        StackTraceElement elem = elems[3];
        String className = Strings.removeLeftByLast(elem.getClassName(), ".");
        
        return new StringBuilder()
            .append("[").append(className).append(".").append(elem.getMethodName()).append("()").append("]")
            .toString();
    }
    
    /**
     * 生成一个新的线程
     * 
     * @param runnable 线程运行类
     * @return Thread
     */
    public static Thread newThread(Runnable runnable)
    {
        return new Thread(runnable);
    }
    
    /**
     * 生成一个新的线程
     * 
     * @param runnable 线程运行类
     * @return Thread
     */
    public static Thread newThread(Runnable runnable, String name)
    {
        return new Thread(runnable, name);
    }
    
    /**
     * 生成一个新的线程
     * 
     * @param group 线程组
     * @param runnable 线程运行类
     * @param sequence 序号
     * @return Thread
     */
    public static Thread newThread(ThreadGroup group, Runnable runnable, int sequence)
    {
        return new Thread(group, runnable, group.getName()+"-"+sequence);
    }
    
    
    
    /**
     * 忽略线程睡眠时的中断异常
     * 
     * @param millis    毫秒数
     */
    public static void sleepIgnoreException(int millis)
    {
        try{Thread.sleep(millis);}catch (InterruptedException e){}
    }
}
